package com.catazy.mvvmlib.base

import android.app.Application
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner
import com.catazy.mvvmlib.ext.lifecycle.ActivityLifecycleCallbacksImpl
import com.catazy.mvvmlib.ext.lifecycle.AppLifecycleObserver
import com.catazy.mvvmlib.util.LogUtil

/**
 * 作者: Tao
 * 日期: 2024/1/24
 * 时间: 16:57
 * 描述: Application的基类
 * 主要作用: 提供一个全局级别的ViewModel
 */
abstract class BaseApplication : Application(), ViewModelStoreOwner {

    companion object {
        lateinit var INSTANCE: BaseApplication
    }

    // ViewModelStore是一个存储ViewModel的容器，ViewModelStoreOwner是一个拥有ViewModelStore的接口
    private lateinit var mAppViewModelStore: ViewModelStore

    // ViewModelProvider.Factory是一个创建ViewModel的工厂接口
    private var mFactory: ViewModelProvider.Factory? = null

    override val viewModelStore: ViewModelStore
        get() = mAppViewModelStore

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
        mAppViewModelStore = ViewModelStore()
        // 初始化日志打印器
        LogUtil.init(isDebug())
        // 是否监听Activity生命周期
        if (isWatchActivityLife()) {
            registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksImpl())
        }
        // 是否监听应用前后台
        if (isWatchAppLife()) {
            ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver)
        }
    }

    /**
     * 通过Factory工厂获取一个全局的ViewModel
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, getAppFactory())
    }

    /**
     * 获取ViewModelProvider.Factory
     */
    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }

    /**
     * 是否是Debug模式
     * @return true:是 false:否 ,默认false
     */
    open fun isDebug(): Boolean = false

    /**
     * 是否监听Activity生命周期
     * @return true:是 false:否 ,默认false
     */
    open fun isWatchActivityLife(): Boolean = false

    /**
     * 是否监听应用前后台
     * @return true:是 false:否 ,默认false
     */
    open fun isWatchAppLife(): Boolean = false
}